import { defineStore } from 'pinia'
import { roleAPI } from '../api'

export const useRoleStore = defineStore('role', {
    state: () => ({
        roles: [],
        searchKeyword: '',
        loading: false,
        error: null
    }),

    getters: {
        filteredRoles: (state) => {
            if (!state.searchKeyword.trim()) {
                return state.roles
            }
            return state.roles.filter(role =>
                role.name?.toLowerCase().includes(state.searchKeyword.toLowerCase()) ||
                role.description?.toLowerCase().includes(state.searchKeyword.toLowerCase())
            )
        }
    },

    actions: {
        async fetchRoles() {
            this.loading = true
            this.error = null
            try {
                this.roles = await roleAPI.getAllRoles()
            } catch (error) {
                this.error = '获取角色列表失败'
                console.error('获取角色失败:', error)
            } finally {
                this.loading = false
            }
        },

        async searchRoles(keyword) {
            this.loading = true
            this.error = null
            try {
                if (keyword?.trim()) {
                    this.roles = await roleAPI.searchRoles(keyword)
                } else {
                    this.roles = await roleAPI.getAllRoles()
                }
            } catch (error) {
                this.error = '搜索角色失败'
                console.error('搜索角色失败:', error)
            } finally {
                this.loading = false
            }
        },

        setSearchKeyword(keyword) {
            this.searchKeyword = keyword
        }
    }
})
